import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  data.forEach(item => {
    const menu = {
      children: [],
      // path: item.menuUrl === 'Layout' ? '/' + (item.route === null ? '' : item.route) : item.route === null ? '' : item.route,
      path:item.path,
      // component:,
      // component: item.menuUrl === 'Layout' ? Layout : (resolve) => require(['@/views/pages' + item.menuUrl], resolve),
      name: item.route,
      // meta: { title: item.menuName, icon: 'form' }
      meta:{title:item.meta.title, icon:item.meta.icon}
    }
    if (item.children) {
      generaMenu(menu.children, item.children)
    }
    routes.push(menu)
  })
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(async resolve => {
      const loadMenuData = []
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      // const { content } = await this.dispatch('user/getUserMenu')
      const content  = [];
      Object.assign(loadMenuData, content)
      const tempAsyncRoutes = Object.assign([], asyncRoutes)
      generaMenu(tempAsyncRoutes, loadMenuData)
      const accessedRoutes = tempAsyncRoutes || []
      accessedRoutes.forEach(item => {
        if (item.component && item.component.name === 'Layout') {
          if (item.children && item.children.length > 0) {
            item.redirect = item.path + '/' + item.children[0].path
            item.alwaysShow = true
          } else {
            item.alwaysShow = true
            // item.redirect = item.path
          }
        }
      })
      const obj = { path: '*', redirect: '/404', hidden: true }
      accessedRoutes.push(obj)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
